# !usr/bin/env python
# -*-coding:utf-8 -*-

# @FileName: receive_logs.py
# @Author:tian
# @Time:06/23/2021

import pika

credentials = pika.PlainCredentials('rain','8800')

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost',
                                                               port=5672,
                                                               virtual_host='/',
                                                               credentials=credentials))
channel = connection.channel()

channel.exchange_declare(exchange='logs',exchange_type='fanout')
# 随机生成一个新的空的queue，将exclusive置为True，这样在consumer从RabbitMQ断开后会删除该queue
result = channel.queue_declare(queue='',exclusive=True)
# 用于获取临时queue的name
queue_name = result.method.queue
# exchange与queue之间的关系成为binding,告诉exchange将message发送该哪些queue
channel.queue_bind(exchange='logs',queue=queue_name)

def callback(ch, method, properties, body):
    print(body.decode())

# 如果该消费者的channel上未确认的消息数达到了prefetch_count数，则不向该消费者发送消息
channel.basic_qos(prefetch_count=1)

channel.basic_consume(queue=queue_name,on_message_callback=callback,auto_ack=True)
channel.start_consuming()